"""
单词计数
"""

# 读取word.txt文件内容
file_path = "/Users/dongjian/Documents/dev_file/word.txt"

f = open(file_path, "r", encoding="UTF-8")
# print(f"文件的全部内容为：{f.readlines()}")

# 这种方式统计单词数量不严谨，例如：name 包含 me单词，但是name ！= me
count = 0
for line in f.readlines():
    line_count = line.count("My")
    count += line_count

print(f"在word.txt文件中，单词is出现的次数为:{count}")


def word_count(file_path_param, word):
    """
    统计文件中某个单词出现的次数
    :param file_path_param: 文件读取路径
    :param word: 指定单词
    :return: count 计数
    """
    count = 0
    with open(file_path_param, "r", encoding="UTF-8") as f:
        for line in f.readlines():
            line = line.strip()  # 去掉开头结尾的空格和换行符
            line_split = line.split(" ")
            for x in line_split:
                if x == word:
                    count += 1
    return count


my_count = word_count(file_path, "My")
print(f"单词My出现的次数为:{my_count}")
